package com.excesys.controller;

import com.excesys.dao.GoodsRepository;
import com.excesys.entity.Goods;
import com.excesys.service.GoodsService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.ArrayList;

@Slf4j
@RestController
public class GoodsController {

    @Resource
    GoodsRepository goodsRepository;

    @Resource
    GoodsService goodsService;

    @Resource
    private ElasticsearchTemplate elasticsearchTemplate;

    @RequestMapping("/get/{id}")
    public Object findOne(@PathVariable String id) {
        Goods goods = new Goods();
        try {
            goods = goodsRepository.findById(id).get();
        } catch (Exception e) {
            return goods;
        }
        return goods;
    }

    @RequestMapping("/goods")
    public Object goods(String key, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "100") Integer size) {
        ModelAndView mav = new ModelAndView();
        try {
            //数据组装
            goodsRepository.saveAll(goodsService.parseDD(key));
            //全文检索关键字
            QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
            if (!ObjectUtils.isEmpty(key)) {
                queryBuilder = QueryBuilders.matchQuery("title", key);
            }
            //构造查询条件和关键字高亮
            SearchQuery searchQuery = new NativeSearchQueryBuilder()
                    .withQuery(queryBuilder)
//                .withSort(SortBuilders.fieldSort("price").order(SortOrder.DESC))
                    .withPageable(PageRequest.of(page - 1, size))
                    .withHighlightBuilder(new HighlightBuilder().field("*").preTags("<span style='color:red'>").postTags("</span>"))
                    .build();
//        Page result = elasticsearchTemplate.queryForPage(searchQuery, Goods.class);
            Page result = goodsRepository.search(searchQuery);
            mav.addObject("goods", result);
        } catch (Exception e) {
            mav.addObject("goods", new ArrayList<>());
        }
        mav.setViewName("goods");
        return mav;
    }

    @RequestMapping({"/", "/index"})
    public Object index(String key, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "100") Integer size) {
        ModelAndView mav = new ModelAndView();
        try {
            //数据组装
            goodsRepository.saveAll(goodsService.parseDD(key));
            //全文检索关键字
            QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
            if (!ObjectUtils.isEmpty(key)) {
                queryBuilder = QueryBuilders.matchQuery("title", key);
            }
            //构造查询条件
            SearchQuery searchQuery = new NativeSearchQueryBuilder()
                    .withQuery(queryBuilder)
//                .withSort(SortBuilders.fieldSort("price").order(SortOrder.DESC))
                    .withPageable(PageRequest.of(page - 1, size))
                    .withHighlightBuilder(new HighlightBuilder().field("*").preTags("<span style='color:red'>").postTags("</span>"))
                    .build();
//        Page result = elasticsearchTemplate.queryForPage(searchQuery, Goods.class);
            Page result = goodsRepository.search(searchQuery);
            mav.addObject("goods", result);
        } catch (Exception e) {
            mav.addObject("goods", new ArrayList<>());
        }
        mav.setViewName("index");
        return mav;
    }

}
